import { Fragment, useEffect, useState } from "react";
import { connect } from "react-redux";
import { setMenuList } from "@/redux/modules/menu/action";
import { setBreadcrumbList } from "@/redux/modules/breadcrumb/action";
import { setAuthRouter } from "@/redux/modules/auth/action";
import { Menu } from "tdesign-react";
import OperationMenu from "./components/operationMenu";
import MenuLogo from "./components/menuLogo";
import type { MenuValue } from "tdesign-react";
import { HomeIcon } from "tdesign-icons-react";
import menuData from "@data/menu.json";
import { useLocation, useNavigate } from "react-router-dom";
import { searchRoute, findAllBreadcrumb } from "@/utils";
import "./index.less";

const { MenuItem, SubMenu } = Menu;
interface RouteItem {
	icon: string;
	title: string;
	path: string;
	children?: RouteItem[];
}
const LayoutMenu = (props: any) => {
	const { pathname } = useLocation();
	const { setBreadcrumbList } = props;
	const [active, setActive] = useState<MenuValue>(pathname);
	const menuList: any = menuData.data;
	const navigate = useNavigate();
	// 图标映射
	const iconMap = {
		HomeIcon: <HomeIcon />
	};
	const renderMenu = (routes: RouteItem[]) => {
		return routes.map(route => {
			if (route.children) {
				// icon={iconMap[route.icon as keyof typeof iconMap]}
				return (
					<SubMenu key={route.path} value={route.path} title={route.title} icon={iconMap[route.icon as keyof typeof iconMap]}>
						{renderMenu(route?.children)}
					</SubMenu>
				);
			}
			return (
				<MenuItem key={route.path} value={route.path} icon={iconMap[route.icon as keyof typeof iconMap]}>
					{route.title}
				</MenuItem>
			);
		});
	};
	const menuChangeBackCall = (v: string) => {
		setActive(v);
		const route = searchRoute(v, menuList);
		if (route.isLink) window.open(route.isLink, "_blank");
		navigate(v);
	};
	useEffect(() => {
		// 存储处理过后的所有面包屑导航栏到 redux 中
		setBreadcrumbList(findAllBreadcrumb(menuList));
		setActive(pathname);
	}, []);
	return (
		<Fragment>
			<Menu
				value={active}
				onChange={(v: any) => menuChangeBackCall(v)}
				logo={<MenuLogo collapse={props.isCollapse} />}
				style={{ marginRight: 20, height: "100%", overflowY: "auto", overflowX: "hidden" }}
				collapsed={props.isCollapse}
				operations={<OperationMenu></OperationMenu>}
				className="layout-side-menu"
			>
				{renderMenu(menuList)}
			</Menu>
		</Fragment>
	);
};

const mapStateToProps = (state: any) => state.menu;
const mapDispatchToProps = { setMenuList, setBreadcrumbList, setAuthRouter };
export default connect(mapStateToProps, mapDispatchToProps)(LayoutMenu);
